package com.woniuxy.patrol.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.common.utils.ResponseUtil;
import com.woniuxy.patrol.pojo.PatrolTaskRoute;
import com.woniuxy.patrol.service.PatrolTaskRouteService;
import com.woniuxy.patrol.mapper.PatrolTaskRouteMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * @author 13162
 * @description 针对表【wcm_patrol_task_route(任务-路线关联表)】的数据库操作Service实现
 * @createDate 2025-07-19 09:34:19
 */
@Service
public class PatrolTaskRouteServiceImpl extends ServiceImpl<PatrolTaskRouteMapper, PatrolTaskRoute>
        implements PatrolTaskRouteService{

    @Resource
    private PatrolTaskRouteMapper taskRouteMapper;

    @Override
    public Map<String, Object> getTodayPatrolTrend(Long communityId) {
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(LocalTime.MAX);

        // 查询今日按小时统计的巡更趋势
        List<Map<String, Object>> trendData = taskRouteMapper.selectTodayTrendByHour(
                startOfDay, endOfDay, communityId);

        // 初始化结果数据结构
        Map<String, List<Integer>> statusCounts = new HashMap<>();
        List<Integer> inspectingCounts = new ArrayList<>(Collections.nCopies(24, 0));
        List<Integer> notInspectedCounts = new ArrayList<>(Collections.nCopies(24, 0));
        List<Integer> completedCounts = new ArrayList<>(Collections.nCopies(24, 0));

        statusCounts.put("巡检中", inspectingCounts);
        statusCounts.put("未巡检", notInspectedCounts);
        statusCounts.put("已完成", completedCounts);

        // 填充数据
        for (Map<String, Object> row : trendData) {
            int hour = Integer.parseInt(row.get("hour").toString());
            int status = Integer.parseInt(row.get("status").toString());
            int count = Integer.parseInt(row.get("count").toString());

            String statusLabel = "";
            switch (status) {
                case 0:
                    statusLabel = "未巡检";
                    break;
                case 1:
                    statusLabel = "巡检中";
                    break;
                case 2:
                    statusLabel = "已完成";
                    break;
            }

            statusCounts.get(statusLabel).set(hour, count);
        }

        // 生成时间标签
        List<String> times = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            times.add(String.format("%02d:00", i));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("times", times);
        result.put("statusCounts", statusCounts);

        return result;
    }
}